
layui.define(['table', 'form'], function(exports){
	
	var $ = layui.$
	,table = layui.table
	,setter = layui.setter
	,form = layui.form;
	//取出当前点击的menuId
	
	var colsArr;
	var tableTitle;//表头标题
	var tableField;//表头标题 有隐藏
	var tableHead;//表头字段  
	var tableSearch = {};//全局搜索条件
   	var parentJson = {};
   loadTable();
	$('.layui-btn').on('click', function(){
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	  });
	  
	 var nameTpl = function (d) {
	      return '<a lay-event="nameTpl" style="cursor: pointer" ><span  style="color:#1E9FFF">' + d.deviceno + '</span></a>';
    };	  
    console.log(nameTpl);
	
	function loadTable(header){
		colsArr = [
			{type: 'checkbox', fixed: 'left'},
			{field: 'deviceno', title: '设备编号',align:'center',sort: false  },
		    {field: 'devicename', title: '设备名称',align:'center',sort: false,templet: nameTpl  },		  
		    {field: 'memo', title: '备注',align:'center',sort: false  },
	     	{field: 'lrr', title: '录入人',align:'center',sort: false  },
	    	{field: 'lrsj', title: '录入时间',align:'center',sort: false  },
		];
		layui.each(colsArr,function(inx,val){
			tableHead += val.hasOwnProperty('field')?val.field:'-';
			tableHead += ',';
			tableTitle += val.hasOwnProperty('title')?(val.hide?'':val.title+','):',';
			tableField += val.hasOwnProperty('field')?(val.hide?'':val.field+','):',';
	 	})
	 	//tableHead是获取表字段
 		tableHead = tableHead.substring(tableHead.indexOf(',')+1,tableHead.length-1);
		//导出时需要用到标题
		tableTitle = tableTitle.substring(tableTitle.indexOf(',')+1,tableTitle.length-1);
		//导出需要用到实际导出的字段
		tableField = tableField.substring(tableField.indexOf(',')+1,tableField.length-1);		
		parentJson.headField = tableHead;
		parentJson.search1 = tableSearch;	
		//用户管理
		table.render({
			elem: '#LAY-genius-table'
			,url: setter.host + '/device/getSelectBody' 
			,cols: [colsArr]
			//,toolbar: 'true'
			//,defaultToolbar: ['print']
			,method:'post'
			,contentType:'application/json; charset=utf-8'
			,where:{'headField':tableHead}
			,page: true
			,limit: 30
			,limits:[30,50,70]
			,height: 'full-80'
			,text: {
				none: '暂无相关数据' 
			}
			,done:function () {
				delete this.where; 
			}
		});
	}

	//事件
	var active = {
		batchdel: function(){
			var checkStatus = table.checkStatus('LAY-genius-table')
			,checkData = checkStatus.data; 

			if(checkData.length === 0){
				return layer.msg('请选择数据');
			}
			layer.prompt({
				formType: 1
				,title: '敏感操作，请验证口令'
			}, function(value, index){
				var command = layui.sessionData('layuiSession').command;
				if(value == command){
					layer.close(index);
					layer.confirm('确定删除吗？', function(index_confirm) {
						layer.close(index_confirm);
						var delIds ={'delData':[]};
						layui.each(checkData,function(inx,checkValue){
							var delId = {};
							delId.deviceno = checkValue.deviceno;
							delIds.delData.push(delId);
						})
						
						console.log(delIds);
						layui.admin.req({
			        	    url: setter.host+'/device/batchdel'
			        	    ,type:'post'
			        	    ,dataType:'json'
			        	    ,contentType: "application/json; charset=utf-8"
			        	    ,data:JSON.stringify(delIds) 
			        	    ,done: function(res){
			        	    	//请求成功后
			        	    	if(res.status == setter.response.statusCode.status_Success){
									table.reload('LAY-genius-table'); 
									layer.msg(res.msg);
								}else{
									layer.msg(res.msg);
								}
			        	    }
						});
					});
				}else{
					layer.msg('口令错误');
				}
			});
		}
		,add: function(){
			var obj = {};
			obj.bakUrl = setter.host+'/device/toSelect';
			obj.jsType = 'add';
			layui.common.postUrl(obj,setter.host+'/device/toInsert');
		}
		,edit: function(){		   
		    var checkStatus = table.checkStatus('LAY-genius-table')
			,checkData = checkStatus.data;            
			if(checkData.length === 0){
				return layer.msg('请选择数据');
			}
			if(checkData.length > 1){
				return layer.msg('只能编辑一行数据');
			}
			checkData[0].bakUrl = setter.host+'/device/toSelect';
			checkData[0].jsType = 'edit';
			console.log(checkData[0]);
			layui.common.postUrl(checkData[0],setter.host+'/device/toEdit');
		}				
		,exportExcel: function(){
			var where = {};
	  		where.search=JSON.stringify(tableSearch);
	  		where.format = "excel";
	  		where.title = tableTitle;
	  		where.field = tableField;
			layui.common.postUrl(where, setter.host+'/device/exportExcel');
		}	
		,exportCsv: function(){
			var where = {};
	    	where.whereKey=JSON.stringify(tableSearch);;
	    	where.format = "csv";
	    	where.title = tableTitle;
	    	where.field = tableField;
			layui.common.postUrl(where, setter.host+'/device/exportExcel');
		}			
	};
	//监听工具条
	table.on('sort(LAY-genius-table)', function(obj){		 	
		table.reload('LAY-genius-table', {
			initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
			,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
				ascField: obj.field //排序字段
		      	,asc: obj.type //排序方式
		      	,headField:tableHead //表头字段
		      	,search: tableSearch //查询字段
			}
		});
	});
	table.on('tool(LAY-genius-table)', function(obj){
		obj.data.bakUrl = setter.host+'/device/toSelect';
		if(obj.event=='nameTpl'){
			console.log(obj.data);
			layui.common.postUrl(obj.data,setter.host+'/device/toSearch');
		}
		
	});
	
	
	//监听搜索
	form.on('submit(LAY-genius-normal-search)', function(data){
		tableSearch = {};	
		if(data.field.devicename != ''){
			tableSearch.devicename = data.field.devicename;
		}	
		table.reload('LAY-genius-table', {
			where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
	    		search: tableSearch //查询字段
	    		,headField:tableHead //表头字段
			}
		});
	});	

	
	exports('select', {})
});

